<!-- 添加受试者 -->
<template>
  <div>
    <a-modal
      width="800"
      :title="$t('all.autotext134')"
      :visible="innerVisible"
      :confirm-loading="confirmLoading"
      :footer="null"
      @cancel="handleCancel"
    >
      <!-- 弹框主体 start -->
      <a-table
        bordered
        :loading="tableLoading"
        :columns="columns"
        :dataSource="data"
        :pagination="false"
      >
        <!-- table template start -->
        <!-- table操作栏 -->
        <template slot="title">
          <span style="display: flex;">
            <a-button style="margin-right: 8px" icon="plus" @click="activeSecondModal">{{ $t('all.autotext176') }}</a-button>
            <a-button icon="download" style="margin-right: 8px" @click="downloadMode">{{ $t('all.autotext626') }}</a-button>
            <a-upload
              style="width: 30%;"
              accept=".xlsx"
              name="file"
              :before-upload="beforeUpload"
              list-type="picture"
              :preview-file="previewFile"
            >
              <a-button v-if="fileList.length < 1"> <a-icon type="upload" @change="handleChange()" /> {{ $t('all.autotext25') }} </a-button>
            </a-upload>
          </span>
        </template>
        <template slot="siteOrgName" slot-scope="text, record">
          <span>{{ record.siteOrgName }}</span>
        </template>
        <!-- table template end -->
        <!-- 动态输入开始 -->
        <template
          v-for="col in ['ptsNo', 'ptsName' , 'guardianName']"
          :slot="col"
          slot-scope="text, record"
        >
          <a-input
            :key="col"
            v-if="record.editable"
            style="margin: -5px 0"
            :value="text"
            :placeholder="placeholder[col]"
            @change="e => handleInputChange(e.target.value, record.key, col)"
          />
          <template v-else>{{ text }}</template>
        </template>
        <template slot="ptsPhone" slot-scope="text, record">
          <template v-if="record.editable">
            <div class="phone-wrapper">
              <a-input
                style="margin: -5px 0"
                key="ptsPhone"
                :value="text"
                :maxLength="11"
                :placeholder="placeholder.ptsPhone"
                @change="e => handleInputChange(e.target.value, record.key, 'ptsPhone')"
                @pressEnter="() => checkPhoneUsed(record)"
                @blur="() => checkPhoneUsed(record)"
              />
              <a-tooltip placement="bottomRight" :overlayStyle="{minWidth:'350px'}">
                <template slot="title">
                  {{ $t('all.autotext418.1') }} {{ record.phoneUsed }} {{ $t('all.autotext418.2') }}
                </template>
                <div class="phone-error" v-if="record.phoneUsed"></div>
              </a-tooltip>
            </div>

            <!-- <div v-if="record.phoneUsed" class="phone-used">手机号已关联受试者{{ record.phoneUsed }}</div> -->
          </template>

          <template v-else>{{ text }}</template>
        </template>
        <!-- 选择操作 -->
        <template slot="ptsTypeRoleId" slot-scope="text, record">
          <a-select
            style="margin: -5px 0; width: 100%"
            :value="text"
            v-if="record.editable"
            :placeholder="placeholder.ptsTypeRoleId"
            @change="e => handleSelectChange(e, record.key, 'ptsTypeRoleId')"
          >
            <a-select-option v-for="item in typelist" :key="item.id" :value="item.id"> {{ item.name }} </a-select-option>
          </a-select>
          <template v-else>{{ text | enumValueBytype(typelist) }}</template>
        </template>
        <!-- 操作模块 -->
        <template slot="operation" slot-scope="text, record, index">
          <template v-if="record.editable">
            <span v-if="record.isNew">
              <a @click="saveRow(record, index)">{{ $t('all.autotext176') }}</a>
              <a-divider type="vertical" />
              <a-popconfirm :title="$t('all.autotext718')" @confirm="remove(record.key)">
                <a>{{ $t('all.autotext379') }}</a>
              </a-popconfirm>
            </span>
            <span v-else>
              <a @click="saveRow(record, index)">{{ $t('all.autotext321') }}</a>
              <a-divider type="vertical" />
              <a @click="cancel(record.key)">{{ $t('all.autotext975') }}</a>
            </span>
          </template>
          <span v-else>
            <a @click="toggle(record.key)">{{ $t('all.autotext919') }}</a>
            <a-divider type="vertical" />
            <a-popconfirm :title="$t('all.autotext718')" @confirm="remove(record.key)">
              <a>{{ $t('all.autotext379') }}</a>
            </a-popconfirm>
          </span>
        </template>
      </a-table>
      <!-- 弹框主体 end -->
      <div class="footer-view">
        <a-space size="middle">
          <a-button @click="handleCancel">{{ $t('all.autotext975') }}</a-button>
          <a-button
            :loading="confirmLoading"
            type="primary"
            @click="handleOk(1)"
            ghost
          >
            {{ $t('all.autotext351') }}
          </a-button>
          <a-button :loading="confirmLoading" type="primary" @click="handleOk(2)" >{{ $t('all.autotext669') }}</a-button>
        </a-space>
      </div>
    </a-modal>

    <!-- 二级弹框 start -->
    <a-modal
      :title="$t('all.autotext1462')"
      :visible="secondVisible"
      @ok="handleSecondOk()"
      @cancel="handleSecondCancel"
      centered
    >
      <!-- 二级弹框表单 -->
      <a-form-model
        ref="ruleForm"
        :model="form"
        :rules="formRules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <a-form-model-item :label="$t('all.autotext955')" prop="researchId">
          <a-select v-model="form.researchId">
            <a-select-option v-for="item in centerList" :value="item.id" :key="item.id">
              {{ item.researchCenterNo }} - {{ item.orgName }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item :label="$t('all.autotext1321')" prop="count">
          <a-input-number
            :max="100"
            :min="1"
            style="width: 100%"
            v-model="form.count"
          />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import { getContractCenter } from '@/api/overview/member'
import { getaAddPtsTable, ptsTypes, exportTemplate, checkByPhone } from '@/api/overview/subject'
import { exportExcel } from '@/utils/util'
import modalMixin from '@/utils/modal.mixin'

export default {
  mixins: [modalMixin],
  name: 'AddVisitModel',
  props: {
    datailId: {
      type: [String, Number],
      default: null
    }
  },
  data () {
    return {
      proId: '',
      fileList: [],
      data: [], // table data
      centerList: [],
      secondVisible: false,
      confirmLoading: false,
      tableLoading: false,
      form: {
        researchId: null,
        count: 1
      },
      formRules: {
        researchId: [{ required: true, message: this.$t('all.autotext1348'), trigger: 'change' }],
        count: [{ required: true, message: this.$t('all.autotext963'), trigger: 'change' }]
      },
      labelCol: { span: 6 },
      wrapperCol: { span: 15 },
      placeholder: {
        ptsNo: this.$t('all.autotext466'),
        ptsTypeRoleId: `${this.$t('all.autotext142')}(${this.$t('required')})`,
        ptsName: `${this.$t('all.autotext282')}(${this.$t('required')})`,
        guardianName: `${this.$t('all.autotext1490')}(${this.$t('required.not')})`,
        ptsPhone: `${this.$t('all.autotext940')}(${this.$t('required')})`
      },
      columns: [
        {
          title: this.$t('all.autotext240'),
          dataIndex: 'key',
          key: 'key'
        },
        {
          title: this.$t('all.autotext949'),
          dataIndex: 'siteOrgName',
          key: 'siteOrgName',
          scopedSlots: { customRender: 'siteOrgName' }
        },
        {
          title: this.$t('all.autotext1357') + '*',
          dataIndex: 'ptsNo',
          key: 'ptsNo',
          scopedSlots: { customRender: 'ptsNo' }
        },
        {
          title: this.$t('all.autotext545') + '*',
          dataIndex: 'ptsTypeRoleId',
          key: 'ptsTypeRoleId',
          width: '15%',
          scopedSlots: { customRender: 'ptsTypeRoleId' }
        },
        {
          title: this.$t('all.autotext56') + '*',
          dataIndex: 'ptsName',
          key: 'ptsName',
          scopedSlots: { customRender: 'ptsName' }
        },
        {
          title: this.$t('all.autotext314'),
          dataIndex: 'guardianName',
          key: 'guardianName',
          scopedSlots: { customRender: 'guardianName' }
        },
        {
          title: this.$t('all.autotext1714') + '*',
          dataIndex: 'ptsPhone',
          key: 'ptsPhone',
          scopedSlots: { customRender: 'ptsPhone' }
        },
        {
          title: this.$t('all.autotext187'),
          key: 'operation',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      typelist: [],
      queryParam: {
        proId: this.datailId
      }
    }
  },
  filters: {
    enumValueBytype (value, enumObj, key = 'desc') {
      if (value == null) {
        return '-'
      }
      let target = ''
      enumObj.forEach(item => {
        if (item.id === parseInt(value)) {
          target = item.name
        }
      })
      return target
    }
  },
  created () {
    const pd = localStorage.getItem('CURRENT_PROID')
    if (pd) {
      this.proId = parseInt(pd)
    }
  },
  methods: {
    modalInit () {
      this.getCenterList()
      this.getPtsTypes()
    },
    async getPtsTypes () {
      const res = await ptsTypes({ proId: this.datailId })
      this.typelist = res
    },
    // 过滤出所选机构的名字将其一起带给form表单
    filterOrgName () {
      const target = this.centerList.find(item => item.id === this.form.researchId)
      return target.orgName
    },
    // 上传文件
    beforeUpload (file) {
      // 定义可选文件类型
      return false
    },
    previewFile (file) {
      const isJpgOrPng = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      if (!isJpgOrPng) {
        this.$notification.error({
          message: file.name,
          description: this.$t('all.autotext1188')
        })
        return false
      } else {
        const params = new FormData()
        params.append('file', file)
        params.append('proId', this.proId)
        return getaAddPtsTable(params).then(res => {
          this.$emit('import')
          this.$notification.success({
            message: file.name,
            description: this.$t('all.autotext946')
          })
        })
      }
    },
    // 上传文件end
    handleChange (info) {
      this.fileList = info.fileList
      this.cUrl = info.fileList[0].response.data
    },
    getCenterList () {
      getContractCenter({ proId: this.proId, deleted: 0 }).then(res => {
        this.centerList = res.content
        if (this.centerList.length > 0) {
          this.form.researchId = this.centerList[0].id
        }
      })
    },
    // 开始添加 批量插入row开始
    activeSecondModal () {
      this.secondVisible = true
      this.form.researchId = this.centerList[0].id
    },
    /* *****************行编辑处理****************** */
    // 删除行
    remove (key) {
      const newData = this.data.filter(item => item.key !== key)
      this.data = newData
    },
    // 行状态切换
    toggle (key) {
      const target = this.data.find(item => item.key === key)
      target._originalData = { ...target }
      target.editable = !target.editable
      this.$forceUpdate()
    },
    // input输入事件
    handleInputChange (value, key, column) {
      const newData = [...this.data]
      const target = newData.find(item => key === item.key)
      if (target) {
        if (column === 'ptsNo') {
          value = this.$options.filters.checkUnChinese(value)
        }
        if (column === 'ptsPhone') {
          target.phoneUsed = false
        }
        target[column] = value
        this.data = newData
      }
    },
    // 校验输入的手机号
    checkPhone (val) {
      const pattern = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/
      return pattern.test(val)
    },
    // select选择事件
    handleSelectChange (value, key, column) {
      const newData = [...this.data]
      const target = newData.find(item => key === item.key)
      if (target) {
        target[column] = value
        this.data = newData
      }
      this.$forceUpdate()
    },
    // 取消事件，还原原本行数据
    cancel (key) {
      const target = this.data.find(item => item.key === key)
      Object.keys(target).forEach(key => {
        target[key] = target._originalData[key]
      })
      target._originalData = undefined
    },
    // 检测手机号是否被使用过
    checkPhoneUsed (record) {
      // 15245845958
      return new Promise((resolve, reject) => {
        if (record.phoneUsed) {
          resolve(true)
          return
        }
        checkByPhone({ phone: record.ptsPhone, proId: this.proId }).then(res => {
          if (Object.keys(res).length === 0) {
            resolve(true)
            return
          }
          const targetIndex = this.data.findIndex(item => item.key === record.key)
          if (typeof res === 'object' && res[record.ptsPhone]) {
            this.tableLoading = false
            this.$set(this.data, targetIndex, { ...record, phoneUsed: res[record.ptsPhone] })
          }
          resolve(false)
        })
      })
    },
    // row保存
    saveRow (record, index) {
      this.tableLoading = true
      this.data[index].ptsTypeRoleIdDesc = this.typelist.find(item => Number(item.id) === Number(record.ptsTypeRoleId)).name
      const { key, ptsNo, ptsTypeRoleId, ptsPhone } = record // 需要校验的必填字段
      if (!ptsNo || !ptsTypeRoleId || !ptsPhone) {
        this.tableLoading = false
        this.$message.error(this.$t('all.autotext89'))
        return
      }
      if (!this.checkPhone(ptsPhone)) {
        this.tableLoading = false
        this.$message.error(this.$t('all.autotext1119'))
        return
      }
      this.checkPhoneUsed(record).then(res => {
        if (res) {
          // 模拟网络请求、卡顿 100ms, 不需要走接口，去掉即可
          new Promise(resolve => {
            setTimeout(() => {
              resolve({ loop: false })
            }, 100)
          }).then(() => {
            const target = this.data.find(item => item.key === key)
            delete target._originalData // 删除克隆字段，防止编辑出现该部分
            // 上面一行最后的“key”是否应为“record.key”?
            target.editable = false
            target.isNew = false
            this.tableLoading = false
          })
        }
      })
    },
    /* *****************弹框回调处理****************** */
    handleOk (type) {
      console.log('组件中data', this.data)
      if (!this.data.length) {
        this.$message.error(this.$t('all.autotext1509'))
        return false
      }
      const flag = this.data.find(item => item.isNew === true)
      if (flag) {
        this.$message.error(this.$t('all.autotext1170'))
        return false
      }
      this.$emit('ok', this.data, type)
    },
    handleCancel () {
      this.innerVisible = false
      this.data = [] // 清空数组
    },
    // 根据填写数据遍历列表
    handleSecondOk () {
      // 校验
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const len = this.data.length
          const count = this.form.count + len
          const siteOrgName = this.filterOrgName()
          for (let i = len; i < count; i++) {
            this.data.push({
              key: i + 1,
              ptsNo: '',
              researchId: this.form.researchId,
              // siteOrgName: this.form.researchId.orgName,
              siteOrgName,
              ptsTypeRoleId: this.typelist.length > 0 ? this.typelist[0].id : undefined,
              ptsPhone: '',
              guardianName: '',
              editable: true,
              isNew: true
            })
          }
          this.handleSecondCancel()
        }
      })
    },
    // 关闭并重置弹窗
    handleSecondCancel () {
      this.secondVisible = false
      setTimeout(() => {
        this.$refs.ruleForm.resetFields()
        this.form = {
          researchId: null,
          count: 1
        }
      }, 200)
    },
    downloadMode () {
      exportTemplate({ proId: this.proId }).then(res => {
        this.$message.success(this.$t('all.autotext638'))
        exportExcel(this.$t('all.autotext66'), res)
      })
    }
  }
}
</script>
<style scoped lang="less">
  .footer-view{
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
  }

  .phone-wrapper{
    position:relative;
    .phone-error{
      background: #FFAD0D;
      width:6px;
      height: 6px;
      border-radius: 50%;
      position:absolute;
      top:50%;
      right:12.5px;
      margin-top: -3px;
    }
  }
</style>
